package com.ruoyi.project.imUtils.impl;

import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.chatroom.ChatRoomListResult;
import cn.jmessage.api.chatroom.ChatRoomMemberList;
import cn.jmessage.api.chatroom.CreateChatRoomResult;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.common.model.UserPayload;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import cn.jmessage.api.message.MessageListResult;
import cn.jmessage.api.resource.UploadResult;
import cn.jmessage.api.user.UserInfoResult;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.imUtils.IMServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


@Service ("jiguang")
public class JiGuanImpl implements IMServer {

    private static final Logger log = LoggerFactory.getLogger(JiGuanImpl.class);

    private final String appkey = "6d3c21662373e17b01f9b169";

    private final String masterSecret = "32f7fc19408397c97c62ea7c";

    private final JMessageClient client = new JMessageClient(this.appkey, this.masterSecret);


    /**
     * 删除聊天室
     */
    public void deleteChatRoom () throws APIConnectionException, APIRequestException {
        ResponseWrapper responseWrapper = this.client.deleteChatRoom(15317450);
    }


    /**
     * 注册用户
     */
    @Override
    public String registerUsers (String userName, String userId, String avatar) throws Exception {

        RegisterInfo.Builder builder = RegisterInfo.newBuilder().setUsername(userId).setPassword(userId)
                .setNickname(userName);
        if (StringUtils.isNotBlank(avatar)) {
            //            UploadResult image = uploadAvatar(avatar, userName);
            //            if(image!=null&&StringUtils.isNotBlank(image.getMediaId())){
            //                builder.setAvatar(image.getMediaId());
            //            }else{
            builder.setAvatar(avatar);
            //            }
        }
        RegisterInfo registerInfo = builder.build();
        RegisterInfo[] registerInfos = new RegisterInfo[1];
        registerInfos[0] = registerInfo;
        return this.client.registerUsers(registerInfos);
    }

    /**
     * 更新用户
     */
    @Override
    public void updateUsers (String userName, String nickName, String avatar) throws Exception {

        UserPayload.Builder builder = UserPayload.newBuilder().setNickname(nickName);
        if (StringUtils.isNotBlank(avatar)) {
            //            UploadResult image = uploadAvatar(avatar,userName);
            //            if(image!=null&&StringUtils.isNotBlank(image.getMediaId())){
            //                builder.setAvatar(image.getMediaId());
            //            }else{
            builder.setAvatar(avatar);
            //            }
        }
        UserPayload payload = builder.build();
        this.client.updateUserInfo(userName, payload);
        UserInfoResult userInfo = this.client.getUserInfo(userName);
        System.out.println("打印用户信息：----------" + JSONObject.toJSONString(userInfo));
    }

    public UploadResult uploadAvatar (String avatar, String userName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(avatar);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(500000);
            is = urlConnection.getInputStream();

            String BOUNDARY = "========7d4a6d158c9";
            URL url2 = new URL("https://api.im.jpush.cn/v1/resource?type=image");
            HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("conn", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            String authCode = ServiceHelper.getBasicAuthorization(this.appkey, this.masterSecret);
            conn.setRequestProperty("Authorization", authCode);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            os = new DataOutputStream(conn.getOutputStream());

            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\"" + avatar + "\"" + "\r\n");
            sb.append("Content-Type:application/octet-stream");
            sb.append("\r\n");
            os.write(sb.toString().getBytes());

            byte[] bufferOut = new byte[1024];

            int len = 0;
            int sum = 0;
            while ((len = is.read(bufferOut)) != -1) {
                os.write(bufferOut, 0, len);
                sum = len + sum;
            }
            System.out.println("上传图片大小为:" + sum);

            os.write("\r\n".getBytes());
            is.close();
            byte[] end_data = ("\r\n--" + BOUNDARY + "--" + "\r\n").getBytes();
            os.write(end_data);
            os.flush();
            os.close();
            int status1 = conn.getResponseCode();
            log.debug("状态值" + status1);
            StringBuffer stringBuffer = new StringBuffer();
            InputStream in = null;
            if (status1 / 100 == 2) {
                in = conn.getInputStream();
            } else {
                in = conn.getErrorStream();
            }

            if (null != in) {
                InputStreamReader responseContent = new InputStreamReader(in, "UTF-8");
                char[] quota = new char[1024];

                int remaining;
                while ((remaining = responseContent.read(quota)) > 0) {
                    stringBuffer.append(quota, 0, remaining);
                }
            }

            ResponseWrapper wrapper = new ResponseWrapper();
            String responseContent1 = stringBuffer.toString();
            wrapper.responseCode    = status1;
            wrapper.responseContent = responseContent1;
            String quota1 = conn.getHeaderField("X-Rate-Limit-Limit");
            String remaining1 = conn.getHeaderField("X-Rate-Limit-Remaining");
            String reset = conn.getHeaderField("X-Rate-Limit-Reset");
            wrapper.setRateLimit(quota1, remaining1, reset);
            if (status1 >= 200 && status1 < 300) {
                log.debug("Succeed to get response OK - responseCode:" + status1);
                log.debug("Response Content - " + responseContent1);
            } else {
                if (status1 < 300 || status1 >= 400) {
                    log.warn("Got error response - responseCode:" + status1 + ", responseContent:" + responseContent1);
                    wrapper.setErrorObject();
                    throw new APIRequestException(wrapper);
                }

                log.warn(
                        "Normal response but unexpected - responseCode:" + status1 + ", responseContent:" + responseContent1);
            }

            return (UploadResult) UploadResult.fromResponse(wrapper, UploadResult.class);
        } catch (MalformedURLException e) {
            System.out.println("url错误:" + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("流错误:" + e.getMessage());
            return null;
        } catch (APIRequestException e) {
            System.out.println("api异常:" + e.getMessage());
            return null;
        }
    }

    /**
     * 注册管理员
     */
    public void registerAdmins () throws APIConnectionException, APIRequestException {

        String string = this.client.registerAdmins("admin", "admin");
    }

    /*
     * 获取用户会话信息
     */
    public MessageListResult ConversationList (String begin_time, String end_time)
            throws APIConnectionException, APIRequestException {

        MessageListResult ms = this.client.getMessageList(500, begin_time, end_time);

        return ms;
    }


    /*
     * 通过聊天室id获取聊天记录
     */
    public ResponseWrapper retractMessage (String username, long msgId)
            throws APIConnectionException, APIRequestException {

        ResponseWrapper ms = this.client.retractMessage(username, msgId);

        return ms;
    }


    /**
     * 用户更新头像
     */
    public void updateUsersAvatar (String userName, String avatar) throws APIConnectionException, APIRequestException {
        UserPayload payload = UserPayload.newBuilder().setAvatar(avatar).build();
        this.client.updateUserInfo(userName, payload);
    }

    /**
     * 用户更新昵称
     */
    public void updateUsersNickName (String userName, String nickName)
            throws APIConnectionException, APIRequestException {
        UserPayload payload = UserPayload.newBuilder().setNickname(nickName).build();
        this.client.updateUserInfo(userName, payload);
    }

    /**
     * 用户禁用
     */
    public void forbidUser (String username, boolean disable) throws APIConnectionException, APIRequestException {
        this.client.forbidUser(username, disable);
    }

    /**
     * 用户删除
     */
    public void deleteUser (String username) throws APIConnectionException, APIRequestException {
        this.client.deleteUser(username);
    }

    /**
     * 创建聊天室
     */
    public String createChatRoom (String username, String roomName) throws APIConnectionException, APIRequestException {
        CreateChatRoomResult chatRoom = this.client.createChatRoom(
                ChatRoomPayload.newBuilder().setOwnerUsername(username).setName(roomName).build());
        return chatRoom.getChatroom_id().toString();
    }

    /**
     * 获取聊天室详情
     */
    public ChatRoomListResult getChatroomInfo (String imId) throws APIConnectionException, APIRequestException {
        ChatRoomListResult result = this.client.getBatchChatRoomInfo(Long.parseLong(imId));
        return result;
    }

    /**
     * 清空聊天室
     */
    public void clearChatRoom (long imid, long userId) throws APIConnectionException, APIRequestException {
        List <String> members = new ArrayList <>();
        ChatRoomMemberList chatRoomMemberList = this.client.getChatRoomMembers(imid, 0, 500);
        for (ChatRoomMemberList.ChatRoomMember chatRoomMember : chatRoomMemberList.getMembers()) {
            if (!chatRoomMember.getUsername().equals(String.valueOf(userId))) {
                members.add(chatRoomMember.getUsername());
            }
        }
        if (members.size() > 0) {
            this.client.removeChatRoomMembers(imid, members.toArray(new String[] {}));
        }
    }


    /**
     * 进入直播间
     */
    public void addChatRoomMember (long roomId, String members) throws APIConnectionException, APIRequestException {
        ResponseWrapper responseWrapper = this.client.addChatRoomMember(roomId, members);
    }


    /**
     * 移除聊天室
     */
    public void removeChatRoomMembers (long roomId, String members) throws APIConnectionException, APIRequestException {
        ResponseWrapper responseWrapper = this.client.removeChatRoomMembers(roomId, members);
    }

}
